import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait

# 1. 打开浏览器（注意：ChromeDriver若配置环境变量，可省略executable_path）
driver = webdriver.Chrome(executable_path='chromedriver.exe')  # 若报错，可替换为 driver = webdriver.Chrome()
driver.maximize_window()

# 2. 先访问淘宝域名（必须先打开目标网站，否则无法添加Cookie）
driver.get("https://www.taobao.com")
time.sleep(2)  # 等待页面加载

# 3. 你的完整Cookie字符串（从浏览器复制的）
cookie_str = "mtop_partitioned_detect=1; _m_h5_tk=cd9a320265856ed6936ad9a935013e7a_1761906080373; _m_h5_tk_enc=f3c124db5e121f2c3188a56d870094a2; t=c7da458ac562eb3c03018b2c7aa0a563; _tb_token_=e5d51e3e17173; thw=cn; sca=40cb6b3c; arms_uid=a2541a45-1fd2-405d-8780-984d7366dd7b; cookie1=BqRwE%2BEyWo6QCrJcqSR3qu1sHctRNVQZ%2BskLCzFAJak%3D; xlly_s=1; aui=3918632117; mt=ci=0_0; cna=SFuLISHnthMCAXQEYMsH8QNl; 3PcFlag=1761898363346; uc1=pas=0&cookie15=Vq8l%2BKCLz3%2F65A%3D%3D&cookie16=WqG3DMC9UpAPBHGz5QBErFxlCA%3D%3D&cookie21=VT5L2FSpczFp&cookie14=UoYY4vPio7FQ0Q%3D%3D&existShop=false; sn=; csg=873833fb; lgc=tb998680071; cancelledSubSites=empty; dnk=tb998680071; existShop=MTc2MTg5ODM3NQ%3D%3D; tracknick=tb998680071; _cc_=WqG3DMC9EA%3D%3D; _l_g_=Ug%3D%3D; sg=179; _nk_=tb998680071; isg=BDQ0YWOm4WMl_3WvE9ZhGtbJBfKmDVj3YwqEv86VwL9COdSD9h0oh-rru3DhwZBP; tfstk=gQUiC5MSNlosTUY6js01jfYb9xSdWVgjV-LxHqHVYvkBBdLTgju0L-CsBSW_nrDE7mZtHAHmoSwl9TQRy5NslmWReahDnijSlx7xuM3eSMaHLTQRy5sZ1qFFelB8nuhSwEuqbAPE8vGD0Kl43D8EGv8ZgFl2L6cjLq8wuhlE8fGxgn8a3W5nGvkquqyq86cjLxuquXlhbAa48yWj3SSmjqMT-fmiU5jJuE4HycDz_vYVUycGCYPZKE8mUXVzKWVOIUNK5yeowRQeS8Va4-rzLwYiAlP3o0aXQ6uq0kE-jkXwovUti0uqxI84tVkIVruPzpcQY5E45RADufaTymDSxs8jD2z-4uyMG_NE7jyjVrBW5AP4NzZ-rZYESmSrCH-zzklETsUecniZOXD7zWa_VQHkc35ht35jbXGse6fHcniZOXDRt6xPfclI1YC.."

# 4. 关键：拆分Cookie为单个键值对，逐个添加（解决核心错误）
# 按 "; " 分割Cookie字符串，得到每个独立的 "name=value"
cookies_list = cookie_str.split("; ")
for cookie in cookies_list:
    # 按第一个 "=" 分割（避免value中包含"="导致拆分错误）
    name, value = cookie.split("=", 1)
    # 构造Selenium要求的Cookie格式，显式指定域名（解决跨域问题）
    cookie_dict = {
        "name": name,
        "value": value,
        "domain": ".taobao.com"  # 淘宝的通用域名，必须带前面的点
    }
    try:
        driver.add_cookie(cookie_dict)
        print(f"成功添加Cookie：{name}")
    except Exception as e:
        # 忽略个别无效Cookie（如临时Cookie），不影响整体登录
        print(f"添加Cookie {name} 失败：{str(e)[:50]}")  # 只显示前50字符，避免输出过长

# 5. 刷新页面，完成免登录
driver.refresh()
print("\n已尝试刷新登录，可观察页面是否显示用户名（如 tb998680071）")

# 6. 验证登录状态（可选：打印当前Cookie，确认添加成功）
cookies = driver.get_cookies()
print("\n当前浏览器中的Cookie名称列表：")
for co in cookies:
    print(co['name'])

# 停留10秒，观察登录结果
time.sleep(3)
